const { createUser, getUserinfo, resetPasswordById } = require('../service/user.service')
const { serverError } = require('../constants/error.type')
const jwt = require('jsonwebtoken')
const { PRIVATE_KEY } = require('../config')

const handleGetUserinfo = async (ctx, next) => {
  const { userId } = ctx.request.body
  const { id } = ctx.state.userinfo || {}
  try {
    const result = await getUserinfo({ userId: userId || id })
    const { password, ...otherInfo } = result.get()
    ctx.body = {
      code: 0,
      message: '获取成功',
      data: otherInfo
    }
  } catch (err) {
    console.error('[handleGetUserinfo error]: ', err)
    return ctx.app.emit('error', serverError, ctx)
  }
  await next()
}

// 登录
const login = async (ctx, next) => {
  const { username } = ctx.request.body
  try {
    const result = await getUserinfo({ username })
    const dataValues = result.get()
    ctx.body = {
      code: 0,
      message: '登录成功',
      data: {
        userId: dataValues.id,
        isAdmin: dataValues.isAdmin,
        username: dataValues.username,
        token: jwt.sign(dataValues, PRIVATE_KEY, { expiresIn: '1d' })
      }
    }
  } catch (err) {
    console.error('[login error]: ', err)
    return ctx.app.emit('error', serverError, ctx)
  }

  await next()
}

// 注册
const register = async (ctx, next) => {
  const { username, password } = ctx.request.body

  try {
    const result = await createUser(username, password)
    ctx.body = {
      code: 0,
      message: '注册成功',
      data: {
        userId: result.id,
        isAdmin: result.isAdmin,
        username: result.username
      }
    }
  } catch (err) {
    console.error('[register error]: ', err)
    return ctx.app.emit('error', serverError, ctx)
  }

  await next()
}

// 重置密码
const resetPassword = async (ctx, next) => {
  const { password } = ctx.request.body
  const { id } = ctx.state.userinfo

  try {
    await resetPasswordById(id, password)
    ctx.body = {
      code: 0,
      message: '修改密码成功'
    }
  } catch (err) {
    console.error('[resetPassword error]: ', err)
    return ctx.app.emit('error', serverError, ctx)
  }

  await next()
}

module.exports = {
  handleGetUserinfo,
  login,
  register,
  resetPassword
}
